{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import os\n",
    "from collections import defaultdict\n",
    "from datetime import datetime, timedelta"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### download dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bash\n",
    "wget http://files.grouplens.org/datasets/movielens/ml-20m.zip\n",
    "unzip ml-20m.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rating_df =  pd.read_csv('./ml-20m/ratings.csv')\n",
    "rating_df[\"timestamp\"] = pd.to_datetime(rating_df['timestamp'], unit='s')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### truncated dateset  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def truncate_dataset(year, month):\n",
    "    truncated_df = rating_df[rating_df[\"timestamp\"] > datetime(year, month, 1)]\n",
    "    truncated_uni_movie_id = truncated_df.movieId.unique()\n",
    "    truncated_uni_user_id = truncated_df.userId.unique()\n",
    "    \n",
    "    # user_id mapping \n",
    "    truncated_user_id = {}\n",
    "    max_user_len = 0\n",
    "    for m_id in truncated_uni_user_id:\n",
    "        truncated_user_id[m_id] = max_user_len\n",
    "        max_user_len += 1\n",
    "    \n",
    "    # item_id mapping \n",
    "    truncated_movie_id = {}\n",
    "    max_movie_len = 0\n",
    "    for m_id in truncated_uni_movie_id:\n",
    "        truncated_movie_id[m_id] = max_movie_len\n",
    "        max_movie_len += 1\n",
    "\n",
    "    print(\"max_user:\", max_user_len, \"max_item:\", max_movie_len)\n",
    "    truncated_df = truncated_df.sort_values(by=\"timestamp\", ascending=False) # sort by timestamp in descending order\n",
    "    truncated_df[\"movieId\"] = truncated_df[\"movieId\"].apply(lambda x: truncated_movie_id[x])\n",
    "    truncated_df[\"userId\"] = truncated_df[\"userId\"].apply(lambda x: truncated_user_id[x])\n",
    "    \n",
    "    df = truncated_df[[\"userId\", \"movieId\", \"timestamp\"]]\n",
    "    a = np.array([tuple(i) for i in df.values], dtype=np.dtype([('user_id', '<i4'), ('item_id', '<i4'), ('timestamp', 'datetime64[D]')]))\n",
    "    np.save('../dataset/user_data_truncated_{}_{}.npy'.format(year, month), a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### generate training records starting from [2010-01-01, 2014-01-01], with time intervals every 6 month"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "os.mkdir(\"../dataset/\")\n",
    "truncate_dataset(2014, 1)\n",
    "for year in [2013, 2012, 2011, 2010]:\n",
    "    for month in [7,1]:\n",
    "        truncate_dataset(year, month)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### generate test dates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_date = datetime(2015,1,1).date()\n",
    "max_date = datetime(2015,3,31).date()\n",
    "os.mkdir(\"../configs/\") \n",
    "with open('../configs/test_dates.txt', 'w') as f:\n",
    "    while test_date + timedelta(days=7) < max_date:\n",
    "        f.write(\"%s\\n\" % test_date)\n",
    "        test_date = test_date + timedelta(days=7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note: by the end of this notebook, you should have a folder named \"dataset\" and \"configs\" under your project folder."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
